package com.link.base.base.wechat.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.coupons.dao.mybatis.mapper.CollectRecordMapper;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.model.Coupons;
import com.link.base.base.coupons.service.CollectRecordService;
import com.link.base.base.coupons.service.CouponsService;
import com.link.base.base.member.model.MemberCard;
import com.link.base.base.wechat.dao.mybatis.mapper.AutoReplyMapper;
import com.link.base.base.wechat.dao.mybatis.mapper.MessageresultMapper;
import com.link.base.base.wechat.model.*;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.model.InputMessage;
import com.link.base.wechat.basic.util.MsgUtil;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.mpnews.model.Article;
import com.link.base.wechat.wxmessage.model.WxMessage;
import com.link.base.wechat.wxmessage.service.WxMessageService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxsubscriber.dao.mybatis.mapper.WxSubscriberMapper;
import com.link.base.wechat.wxsubscriber.model.Subscriber;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.JsonUtil;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信自动回复实现类
 *
 * @author 路江
 * @date 2018-05
 */
@Service
public class AutoReplyServiceImpl extends BasicServiceImpl<AutoReply> implements AutoReplyService {

    @Resource
    private AutoReplyMapper autoReplyMapper;
    @Resource
    private AutoreplyKeyService autoreplyKeyService;
    @Resource
    private AutoReplyService autoReplyService;
    @Resource
    private AutoreplyContentService autoreplyContentService;
    @Resource
    private WxMessageService wxMessageService;
    @Resource
    private AccountService accountService;
    @Resource
    private ArticlesService articlesService;
    @Resource
    private WxImageService wxImageService;
    @Resource
    private CouponsService couponsService;
    @Resource
    private CollectRecordService collectRecordService;

    @Resource
    private CollectRecordMapper collectRecordMapper;
    @Resource
    private WxPlatformService wxPlatformService;

    @Resource
    private WxSubscriberMapper wxSubscriberMapper;
    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private MessageresultMapper messageresultMapper;

    @Resource
    private WxTokenService wxTokenService;

    @Resource
    private Environment env;

    @Override
    public BasicMapper<AutoReply> getBasicMapper() {
        return autoReplyMapper;
    }

    /**
     * 查询字段回复
     *
     * @author 路江
     * @date 2018
     * @param entity 
     * @return
     */
    @Override
    public Map<String, Object> queryautoReply(AutoReply entity) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        List<AutoReply> listo = new ArrayList<>();
        // 得到回复规则，根据规则id去查询对应的关键字和回复内容
        List<AutoReply> autoReplies = autoReplyService.queryByExamplePage(entity);
        String  subscribe = "subscribe";
        if (subscribe.equals(entity.getType())) {
            subscribeType(autoReplies,map,entity);
        } else {
            for (int i = 0; i < autoReplies.size(); i++) {
                AutoreplyContent autoreplyContent = new AutoreplyContent();
                autoreplyContent.setRuleId(autoReplies.get(i).getId());
                autoreplyContent.setLoginCorpId(autoReplies.get(i).getLoginCorpId());
                autoreplyContent.setPageFlag(false);
                List<AutoreplyContent> contents = new ArrayList<>();
                contents = autoreplyContentService.queryByExamplePage(autoreplyContent);
                AutoreplyKey autoreplyKey = new AutoreplyKey();
                autoreplyKey.setRuleId(autoReplies.get(i).getId());
                autoreplyKey.setLoginCorpId(autoReplies.get(i).getLoginCorpId());
                autoreplyKey.setPageFlag(false);
                autoreplyKey.setWxNumber(entity.getWxUsername());
                List<AutoreplyKey> autoreplyKeys = new ArrayList<>();
                autoreplyKeys = autoreplyKeyService.queryByExamplePage(autoreplyKey);
                AutoReply auto = new AutoReply();
                auto.setRuleName(autoReplies.get(i).getRuleName());
                String keyword = "";
                for (int j = 0; j < autoreplyKeys.size(); j++) {
                    if (null != autoreplyKeys.get(j).getKeyName()) {
                        if (j == autoreplyKeys.size() - 1) {
                            keyword += autoreplyKeys.get(j).getKeyName();
                        } else {
                            keyword += autoreplyKeys.get(j).getKeyName() + " ,";
                        }

                    }
                }
                auto.setKeyword(keyword);
                int text = 0;
                int image = 0;
                int mpnews = 0;
                int wxcard = 0;
                for (int j = 0; j < contents.size(); j++) {
                    if (("text").equals(contents.get(j).getContentType())) {
                        text++;
                    } else if (("image").equals(contents.get(j).getContentType())) {
                        image++;
                    } else if (("mpnews").equals(contents.get(j).getContentType())) {
                        mpnews++;
                    } else if (("wxcard").equals(contents.get(j).getContentType())) {
                        wxcard++;
                    }
                }
                // 拼凑字符串给前端
                String content = (text + image + mpnews + wxcard) + "条（" + text + "条文字， " + image + "张图片，" + mpnews
                        + "条图文，" + wxcard + "张优惠券)";
                auto.setContent(content);
                auto.setReplyMode(autoReplies.get(i).getReplyMode());
                auto.setCreated(autoReplies.get(i).getCreated());
                auto.setId(autoReplies.get(i).getId());
                listo.add(auto);
                map.put("rows", listo);
            }
            AutoReply size = new AutoReply();
            size.setPageFlag(false);
            size.setWxUsername(entity.getWxUsername());
            size.setRuleName(entity.getRuleName());
            size.setType(entity.getType());
            size.setKeyword(entity.getKeyword());
            map.put("total", autoReplyService.queryByExamplePage(size).size());
        }
        return map;
    }

    /**
     * 关注回复
     *
     * @author 路江
     * @date 2018
     * @param autoReplies
     * @param map
     * @param entity
     * @throws Exception
     */
    private void subscribeType(List<AutoReply> autoReplies, Map<String,Object> map, AutoReply entity) throws Exception {
        List<AutoReplys> replys = new ArrayList<>();
        for (int i = 0; i < autoReplies.size(); i++) {
            AutoreplyContent autoreplyContent = new AutoreplyContent();
            autoreplyContent.setRuleId(autoReplies.get(i).getId());
            autoreplyContent.setLoginCorpId(autoReplies.get(i).getLoginCorpId());
            autoreplyContent.setPageFlag(false);
            List<AutoreplyContent> contents = new ArrayList<>();
            contents = autoreplyContentService.queryByExamplePage(autoreplyContent);
            //将对应素材查询出返回前端
            for (int j = 0; j < contents.size(); j++) {
                AutoreplyContent content = contents.get(j);
                if ("mpnews".equals(content.getContentType()) && null != content.getContent()) {
                    Article articles = new Article();
                    articles.setMediaId(content.getContent());
                    List<Article> articlesList = articlesService.queryByExamplePage(articles);
                    if (articlesList.size() != 0) {
                        articles = articlesList.get(0);
                        content.setArticles(articles);
                    }
                }
                if ("image".equals(content.getContentType()) && null != content.getContent()) {
                    WxImage articles = new WxImage();
                    articles.setThumbMediaId(content.getContent());
                    List<WxImage> articlesList = wxImageService.queryByExamplePage(articles);
                    if (articlesList.size() != 0) {
                        articles = articlesList.get(0);
                        content.setImage(articles);
                    }
                }
                if ("wxcard".equals(content.getContentType()) && null != content.getContent()) {
                    Coupons articles = new Coupons();
                    articles.setWeChatCouponId(content.getContent());
                    List<Coupons> articlesList = couponsService.queryByExamplePage(articles);
                    if (articlesList.size() != 0) {
                        articles = articlesList.get(0);
                        content.setCoupons(articles);
                    }
                }
            }
            AutoreplyKey autoreplyKey = new AutoreplyKey();
            autoreplyKey.setRuleId(autoReplies.get(i).getId());
            autoreplyKey.setLoginCorpId(autoReplies.get(i).getLoginCorpId());
            autoreplyKey.setPageFlag(false);
            autoreplyKey.setWxNumber(entity.getWxUsername());
            List<AutoreplyKey> autoreplyKeys = new ArrayList<>();
            autoreplyKeys = autoreplyKeyService.queryByExamplePage(autoreplyKey);
            AutoReplys autoReplys = new AutoReplys();
            AutoReply autoReply = autoReplies.get(i);
            autoReplys.setType(autoReply.getType());
            autoReplys.setRuleName(autoReply.getRuleName());
            autoReplys.setReplyMode(autoReply.getReplyMode());
            autoReplys.setWxUsername(autoReply.getWxUsername());
            autoReplys.setIskeyword(autoReply.getIskeyword());
            autoReplys.setAutoreplyContents(contents);
            autoReplys.setAutoreplyKeys(autoreplyKeys);
            replys.add(autoReplys);
        }
        entity.setPageFlag(false);
        map.put("total", autoReplyService.queryByExamplePage(entity).size());
        map.put("result", replys);
    }

    /**
     * 新增自动回复
     *
     * @author 路江
     * @date 2018
     * @param autoReplys 自动回复对象数据
     * @return
     */
    @Override
    public Map<String, Object> insertAutoReply(AutoReplys autoReplys) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        AutoReply autoReply = new AutoReply();
        autoReply.setReplyMode(autoReplys.getReplyMode());
        autoReply.setType(autoReplys.getType());
        autoReply.setIskeyword(autoReplys.getIskeyword());
        autoReply.setWxUsername(autoReplys.getWxUsername());
        autoReply.setRuleName(autoReplys.getRuleName());
        // 将对应信息存入相应表中
        String subscribe = "subscribe";
        if (subscribe.equals(autoReplys.getType())) {
            for (int i = 0; i < autoReplys.getAutoreplyContents().size(); i++) {
                autoReply.setId(this.keyGenerateService.keyGenerate());
                autoReplyService.insert(autoReply);
                Long ruleId = autoReply.getId();
                autoReplys.getAutoreplyContents().get(i).setRuleId(ruleId);
                autoreplyContentService.insert(autoReplys.getAutoreplyContents().get(i));
            }
        } else {
            autoReplyService.insert(autoReply);
            Long ruleId = autoReply.getId();
            for (int i = 0; i < autoReplys.getAutoreplyKeys().size(); i++) {
                autoReplys.getAutoreplyKeys().get(i).setRuleId(ruleId);
                autoReplys.getAutoreplyKeys().get(i).setWxNumber(autoReplys.getWxUsername());
                autoreplyKeyService.insert(autoReplys.getAutoreplyKeys().get(i));
            }
            for (int i = 0; i < autoReplys.getAutoreplyContents().size(); i++) {
                autoReplys.getAutoreplyContents().get(i).setRuleId(ruleId);
                autoreplyContentService.insert(autoReplys.getAutoreplyContents().get(i));
            }
        }
        return map;
    }

    /**
     * 删除自动回复
     *
     * @author 路江
     * @date 2018
     * @param id 记录id
     * @return
     */
    @Override
    public Map<String, Object> deleteAutoReply(Long id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        // 删除所有关联表，通过规则id关联
        AutoReply autoReplie = autoReplyService.queryById(id);
        AutoreplyContent autoreplyContent = new AutoreplyContent();
        autoreplyContent.setRuleId(autoReplie.getId());
        autoreplyContent.setLoginCorpId(autoReplie.getLoginCorpId());
        autoreplyContent.setPageFlag(false);
        List<AutoreplyContent> contents = autoreplyContentService.queryByExamplePage(autoreplyContent);
        for (int i = 0; i < contents.size(); i++) {
            autoreplyContentService.deleteById(contents.get(i));
        }
        AutoreplyKey autoreplyKey = new AutoreplyKey();
        autoreplyKey.setRuleId(autoReplie.getId());
        autoreplyKey.setLoginCorpId(autoReplie.getLoginCorpId());
        autoreplyKey.setPageFlag(false);
        autoreplyKey.setWxNumber(autoReplie.getWxUsername());
        List<AutoreplyKey> autoreplyKeys = autoreplyKeyService.queryByExamplePage(autoreplyKey);
        for (int i = 0; i < autoreplyKeys.size(); i++) {
            autoreplyKeyService.deleteById(autoreplyKeys.get(i));
        }
        AutoReply param = new AutoReply();
        param.setId(id);
        autoReplyService.deleteById(param);
        return map;
    }

    @Override
    public Map<String, Object> queryAutoReplyById(Long id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        // 根据规则查出使用该规则的key content
        AutoReply autoReplie = autoReplyService.queryById(id);
        AutoreplyContent autoreplyContent = new AutoreplyContent();
        autoreplyContent.setRuleId(autoReplie.getId());
        autoreplyContent.setLoginCorpId(autoReplie.getLoginCorpId());
        autoreplyContent.setPageFlag(false);
        List<AutoreplyContent> contents = new ArrayList<>();
        contents = autoreplyContentService.queryByExamplePage(autoreplyContent);
        //将对应素材查询出返回前端
        for (int j = 0; j < contents.size(); j++) {
            AutoreplyContent content = contents.get(j);
            if ("mpnews".equals(content.getContentType()) && null != content.getContent()) {
                Article articles = new Article();
                articles.setMediaId(content.getContent());
                List<Article> articlesList = articlesService.queryByExamplePage(articles);
                if (articlesList.size() > 0) {
                    content.setArticles(articlesList.get(0));
                }

            }
            if ("image".equals(content.getContentType()) && null != content.getContent()) {
                WxImage articles = new WxImage();
                articles.setThumbMediaId(content.getContent());
                List<WxImage> list = wxImageService.queryByExamplePage(articles);
                if (list.size() > 0) {
                    content.setImage(list.get(0));
                }
            }
            if ("wxcard".equals(content.getContentType()) && null != content.getContent()) {
                Coupons articles = new Coupons();
                articles.setWeChatCouponId(content.getContent());
                List<Coupons> list  = couponsService.queryByExamplePage(articles);
                if (list.size() > 0) {
                    content.setCoupons(list.get(0));
                }
            }
        }
        AutoreplyKey autoreplyKey = new AutoreplyKey();
        autoreplyKey.setRuleId(autoReplie.getId());
        autoreplyKey.setLoginCorpId(autoReplie.getLoginCorpId());
        autoreplyKey.setPageFlag(false);
        autoreplyKey.setWxNumber(autoReplie.getWxUsername());
        List<AutoreplyKey> autoreplyKeys = new ArrayList<>();
        autoreplyKeys = autoreplyKeyService.queryByExamplePage(autoreplyKey);
        AutoReplys autoReplys = new AutoReplys();
        autoReplys.setAutoreplyContents(contents);
        autoReplys.setAutoreplyKeys(autoreplyKeys);
        autoReplys.setType(autoReplie.getType());
        autoReplys.setReplyMode(autoReplie.getReplyMode());
        autoReplys.setRuleName(autoReplie.getRuleName());
        autoReplys.setWxUsername(autoReplie.getWxUsername());
        autoReplys.setIskeyword(autoReplie.getIskeyword());
        autoReplys.setId(autoReplie.getId());
        autoReplys.setCreated(autoReplie.getCreated());
        map.put("rows", autoReplys);

        return map;
    }

    @Override
    public Map<String, Object> updateAutoReplyById(AutoReplys autoReplys) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        AutoReply autoReply = new AutoReply();
        autoReply.setReplyMode(autoReplys.getReplyMode());
        autoReply.setType(autoReplys.getType());
        autoReply.setIskeyword(autoReplys.getIskeyword());
        autoReply.setWxUsername(autoReplys.getWxUsername());
        autoReply.setRuleName(autoReplys.getRuleName());
        autoReply.setId(autoReplys.getId());

        // 修改关联表
        autoReplyService.update(autoReply);
        Long ruleId = autoReply.getId();
        AutoreplyKey autoreplyKey = new AutoreplyKey();
        autoreplyKey.setRuleId(ruleId);
        List<AutoreplyKey> autoreplyKeyList = autoreplyKeyService.queryAll(autoreplyKey);
        for (AutoreplyKey autoreplyKey1 : autoreplyKeyList) {
            autoreplyKeyService.deleteById(autoreplyKey1);
        }
        for (int i = 0; i < autoReplys.getAutoreplyKeys().size(); i++) {
            autoReplys.getAutoreplyKeys().get(i).setRuleId(ruleId);
            autoReplys.getAutoreplyKeys().get(i).setWxNumber(autoReplys.getWxUsername());
            autoreplyKeyService.insert(autoReplys.getAutoreplyKeys().get(i));
        }
        AutoreplyContent autoreplyContent = new AutoreplyContent();
        autoreplyContent.setRuleId(ruleId);
        List<AutoreplyContent> autoreplyContentList = autoreplyContentService.queryAll(autoreplyContent);
        for (AutoreplyContent autoreplyContent1 : autoreplyContentList) {
            autoreplyContentService.deleteById(autoreplyContent1);
        }
        for (int i = 0; i < autoReplys.getAutoreplyContents().size(); i++) {
            autoReplys.getAutoreplyContents().get(i).setRuleId(ruleId);
            autoreplyContentService.insert(autoReplys.getAutoreplyContents().get(i));
        }
        return map;
    }

    @Override
    public String processWxRequest(InputMessage inputMsg) throws Exception {
        // 发送方帐号（open_id）
        String fromUserName = inputMsg.getFromUserName();
        // 公众帐号,对应微信公众号
        String toUserName = inputMsg.getToUserName();
        // 消息类型 （文本，事件,）
        String msgType = inputMsg.getMsgType();
        // 获取消息内容
        String content = inputMsg.getContent();
        // 菜单自定义点击事件
        String eventKey = inputMsg.getEventKey();
        // 返回结果
        String respMessage = "ok";
        AutoReply autoReply = new AutoReply();
        List<AutoReply> autoReplys = new ArrayList<>();
        AutoreplyContent entity = new AutoreplyContent();
        AutoreplyKey autoreplyKey = new AutoreplyKey();
        List<AutoreplyContent> contents = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //交互方式
        String type = "";
        // 得到token
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setWx_og_id(toUserName);
        try {
            WxPlatform platform = wxPlatformService.queryByExamplePage(wxPlatform).get(0);
            String accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
            // 文本消息：关键字回复，粉丝发消息回复
            if ((MsgUtil.MESSAGE_TYPE_TEXT).equals(msgType)) {
                //交互方式
                type = "KeyWordRsp";
                // 首先先将粉丝发过来的信息存储一下
                Messageresult followerMsg = new Messageresult();
                followerMsg.setDate(formatter.format(new Date()));
                followerMsg.setTouser(toUserName);
                //发送方
                followerMsg.setFromUser(fromUserName);
                followerMsg.setWxId(String.valueOf(platform.getId()));
                // 已发送
                followerMsg.setStatus("Succeeded");
                followerMsg.setContentType(msgType);
                followerMsg.setContent(content);
                followerMsg.setType("FollowerMsg");
                followerMsg.setResult("OK");
                followerMsg.setOpenid(fromUserName);
                followerMsg.setWxusername(toUserName);
                Long receptionId = keyGenerateDao.keyGenerate();
                followerMsg.setId(receptionId);
                followerMsg.interfaceCreateData(platform.getLastUpdatedBy(),platform.getLastUpdatedBy(),platform.getCorpid());
                messageresultMapper.followerMsgInsertByInterface(followerMsg);
                // 查询该微信公众号下的所有关键字
                autoreplyKey.setWxNumber(toUserName);
                autoreplyKey.setLoginCorpId(platform.getCorpid());
                autoreplyKey.setPageFlag(false);
                // 得到该微信公众号下所有关键字
                List<AutoreplyKey> autoreplyKeys = autoreplyKeyService.queryByExamplePage(autoreplyKey);
                for (int i = 0; i < autoreplyKeys.size(); i++) {
                    if (content.indexOf(autoreplyKeys.get(i).getKeyName()) != -1) {
                        // 先不完全匹配得到所有规则
                        autoReply = autoReplyService.queryById(autoreplyKeys.get(i).getRuleId());
                        // 如果得到的规则又是不完全匹配的话继续下一个判断；ExactMatch为完全匹配
                        if (("ExactMatch").equals(autoreplyKeys.get(i).getMethod())
                                && (!content.equals(autoreplyKeys.get(i).getKeyName()))) {
                            autoReply = null;
                            continue;
                        }
                        autoReplys.add(autoReply);
                    }
                }
                // 查询回复内容list
                for (int i = 0; i < autoReplys.size(); i++) {
                    List<AutoreplyContent> contentsa = new ArrayList<>();
                    if (null != autoReplys.get(i)) {
                        entity.setRuleId(autoReplys.get(i).getId());
                        entity.setLoginCorpId(platform.getCorpid());
                        entity.setPageFlag(false);
                        contentsa = autoreplyContentService.queryByExamplePage(entity);
                    }
                    sendMsg(contentsa, platform, type, fromUserName, autoReplys.get(i), accessToken, formatter);
                }
                if (contents.size() < 1) {
                    AutoreplyContent autoreplyContent = new AutoreplyContent();
                    AutoReply autoReplyT = new AutoReply();
                    autoReplyT.setWxUsername(toUserName);
                    autoReplyT.setRuleName("非关键字");
                    autoReplyT.setPageFlag(false);
                    autoReplyT.setLoginCorpId(platform.getCorpid());
                    List<AutoReply> contentsa = autoReplyService.queryByExamplePage(autoReplyT);
                    if (contentsa.size() > 0) {
                        autoreplyContent.setContentType(contentsa.get(0).getContentType());
                        autoreplyContent.setContent(contentsa.get(0).getContent());
                        contents.add(autoreplyContent);
                        sendMsg(contents,platform,type,fromUserName,null,accessToken,formatter);
                    }
                }
                return respMessage;
                // 事件：关注，领取优惠券，使用优惠券，自定义菜单点击事件
            } else if ((MsgUtil.EVENT_TYPE).equals(msgType)) {
                // 事件类型
                String eventType = inputMsg.getEvent();
                // 用户领取优惠券
                String userGetCard = "user_get_card";
                String userConsumeCard = "user_consume_card";
                //激活会员卡事件
                String memberCard = "submit_membercard_user_info";
                // 用户删除卡券
                String userDelCard = "user_del_card";
                if ((userGetCard).equals(eventType)) {
                    // 用户删除会员卡后可重新找回，当用户本次操作为找回时，该值为1
                    String regetCard = "1";
                    String isRestoreMemberCard = inputMsg.getIsRestoreMemberCard();
                    // 如果用户重新领回，则做更新
                    if (isRestoreMemberCard.equals(regetCard)) {
                        // 重新领取会员卡的状态
                        String status = "Activated";
                        this.updUserCard(inputMsg, accessToken, status);
                    } else {
                        Map<String, Object> getcartmap = new HashMap<>(16);
                        getcartmap.put("openid", fromUserName);
                        getcartmap.put("card_id", inputMsg.getCardId());
                        // 构造出他想要的json字符串
                        String openid4data = JsonUtil.toString(getcartmap);
                        String url = env.getProperty("weixinuri.getCardListUrl").replace("ACCESS_TOKEN", accessToken);
                        JSONObject json = WeixinHttpUtil.httpRequest(url, "POST", openid4data);
                        List<Map<String, String>> object = (List<Map<String, String>>) json.get("card_list");
                        List<String> codeList = new ArrayList<>();
                        for (int i = 0; i < object.size(); i++) {
                            codeList.add(object.get(i).get("code"));
                        }
                        // 领取记录表保存 待续
                        // 利用openid查出acctId
                        Account account = new Account();
                       // account.setWxOwnOpenId(fromUserName);
                        account.setLoginCorpId(platform.getCorpid());
                        account.setPageFlag(false);
                        List<Account> accounts = accountService.queryByExamplePage(account);
                        Long acctId = accounts.get(0).getId();
                        for (int i = 0; i < codeList.size(); i++) {
                            CollectRecord collectRe = new CollectRecord();
                            collectRe.setAccntId(acctId);
                            collectRe.setCouponsId(Long.valueOf(inputMsg.getCardId()));
                            collectRe.setClaimStatus("Received");
                            collectRe.setReceiveChannel("WeChat");
                            collectRe.setLoginCorpId(platform.getCorpid());
                            collectRe.setPageFlag(false);
                            collectRe.setWechatCode(codeList.get(i));
                            List<CollectRecord> collectRecords = collectRecordService.queryByExamplePage(collectRe);
                            if (collectRecords.size() > 0) {
                                codeList.remove(codeList.get(i));
                            }
                        }
                        for (int i = 0; i < codeList.size(); i++) {
                            if (accounts.size() > 0) {
                                CollectRecord collectRecord = new CollectRecord();
                                //优惠券id
                                Long cardId = getCardId(Long.valueOf(inputMsg.getCardId()),platform.getCorpid());
                                //查询优惠券信息
                                Coupons coupons = new Coupons();
                                coupons.setId(cardId);
                                coupons.setLoginCorpId(platform.getCorpid());
                                coupons = couponsService.queryById(coupons);
                                collectRecord.setCouponsId(cardId);
                                collectRecord.setAccntId(acctId);
                                collectRecord.setClaimTime(formatter.format(new Date()));
                                // 默认一张
                                collectRecord.setClaimantNum(1);
                                // 领取渠道 微信\
                                collectRecord.setReceiveChannel("WeChat");
                                // 只能领取一张，所以只取第一个code
                                collectRecord.setWechatCode(codeList.get(i));
                                //领取时间
                                collectRecord.setClaimTime(formatter.format(new Date()));
                                collectRecord.setClaimStatus("Received");
                                collectRecord.setEffectStaTime(coupons.getEffectStaTime());
                                collectRecord.setEffectEndTime(coupons.getEffectEndTime());
                                Long receptionId = keyGenerateDao.keyGenerate();
                                collectRecord.setId(receptionId);
                                collectRecord.setLoginCorpId(platform.getCorpid());
                                collectRecord.interfaceCreateData(platform.getLastUpdatedBy(),platform.getLastUpdatedBy(),platform.getCorpid());
                                collectRecordMapper.collectRecordInsertByInterface(collectRecord);
                            }
                        }
                    }
                    // 关注微信公众号
                } else if ((MsgUtil.EVENT_TYPE_SUBSCRIBE).equals(eventType)) {
                    //交互方式
                    type = "OnFollowingRsp";
                    autoReply.setWxUsername(toUserName);
                    autoReply.setType("subscribe");
                    autoReply.setLoginCorpId(platform.getCorpid());
                    autoReply.setPageFlag(false);
                    List<AutoReply> autoReplies = autoReplyService.queryByExamplePage(autoReply);
                    for (int i = 0; i < autoReplies.size(); i++) {
                        entity.setRuleId(autoReplies.get(i).getId());
                        entity.setLoginCorpId(platform.getCorpid());
                        entity.setPageFlag(false);
                        List<AutoreplyContent> conts = autoreplyContentService.queryByExamplePage(entity);
                        contents.addAll(conts);
                    }
                    // 自定义菜单点击事件
                } else if ((MsgUtil.EVENT_TYPE_CLICK).equals(eventType)) {
                    //交互方式
                    type = "MenuClickMsg";
                    autoReply.setKeyword(eventKey);
                    autoReply.setType("click");
                    autoReply.setLoginCorpId(platform.getCorpid());
                    autoReply.setPageFlag(false);
                    List<AutoReply> autoReplies = autoReplyService.queryByExamplePage(autoReply);
                    if (autoReplies.size() > 0) {
                        AutoreplyContent autoreplyContent = new AutoreplyContent();
                        autoreplyContent.setContent(autoReplies.get(0).getContent());
                        autoreplyContent.setContentType(autoReplies.get(0).getContentType());
                        contents.add(autoreplyContent);
                    }

                } else if (userConsumeCard.equals(eventType)) {
                    LCLogger.info().withMessage("优惠券已经使用");
                    //激活会员卡
                } else if (memberCard.equals(eventType)) {
                    this.memberCardEvent(inputMsg,accessToken);
                    // 用户删除会员卡
                } else if (userDelCard.equals(eventType)) {
                    // 删除会员卡的状态
                    String status = "Deleted";
                    this.updUserCard(inputMsg, accessToken, status);
                }
            }
            sendMsg(contents,platform,type,fromUserName,autoReply,accessToken,formatter);
        } catch (Exception e) {
            respMessage = "fail";
            LCLogger.withException(e);
        }
        return respMessage;
    }

    /**
     * 发送消息
     * @author 路江
     * @date 2018
     * @param contents 自动回复内容
     * @param platform 公众号信息
     * @param type 类型
     * @param fromUserName openid
     * @param autoReply
     */
    private void sendMsg(List<AutoreplyContent> contents, WxPlatform platform, String type,
                         String fromUserName, AutoReply autoReply,String accessToken,SimpleDateFormat formatter) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        map.put("touser", fromUserName);
        for (int i = 0; i < contents.size(); i++) {
            WxMessage message = new WxMessage();
            message.setMsgType(contents.get(i).getContentType());
            message.setContents(contents.get(i).getContent());
            message.setFromUserName(fromUserName);
            int rs = wxMessageService.wxSendMsg(message,platform.getWx_app_id());
            Messageresult result = new Messageresult();
            result.setTouser(fromUserName);
            result.setDate(formatter.format(new Date()));
            result.setContent(contents.get(i).getContent());
            result.setContentType(contents.get(i).getContentType());
            result.setStatus("Failed");
            result.setType(type);
            result.setResult(rs + "");
            result.setWxId(String.valueOf(platform.getId()));
            result.setFromUser(platform.getWx_og_id());
            result.setOpenid(fromUserName);
            result.setWxusername(platform.getWx_og_id());
            if (rs == 1) {
                result.setStatus("Succeeded");
            }
            Long receptionId = keyGenerateDao.keyGenerate();
            result.setId(receptionId);
            result.interfaceCreateData(platform.getLastUpdatedBy(),platform.getLastUpdatedBy(),platform.getCorpid());
            messageresultMapper.followerMsgInsertByInterface(result);
            // 如果随机回复一条的话，发了一条之后结束
            // 回复规则：RandomMessage 随机一条。AllMessages 全部回复
            if (null != autoReply) {
                if (("RandomMessage").equals(autoReply.getReplyMode())) {
                    break;
                }
            }
        }
    }

    /**
     * 获取卡卷行id
     *
     * @author 路江
     * @param cardId 卡券id
     * @param corpid 账套id
     * @return
     */
    private Long getCardId(Long cardId, Long corpid) throws Exception {
        //分不清领取的是会员卡还是优惠券，用卡卷id去两张表里面查，匹配出来
        Coupons coupons = new Coupons();
        coupons.setWeChatCouponId(cardId.toString());
        coupons.setLoginCorpId(corpid);
        coupons.setPageFlag(false);
        List<Coupons> cList = couponsService.queryByExamplePage(coupons);
        if (cList.size() > 0) {
            cardId = cList.get(0).getId();
        }
        MemberCard memberCard = new MemberCard();
        memberCard.setWeChatCardId(String.valueOf(cardId));
        memberCard.setLoginCorpId(corpid);
        memberCard.setPageFlag(false);
//        List<MemberCard> mList = memberCardMapper.queryByExamplePage(memberCard);
//        if (mList.size() > 0) {
//            cardId = mList.get(0).getId();
//        }
        // TODO: 2019-11-01 会员卡迁移之后的待修改
        return  cardId;
    }

    /**
     * 激活会员卡
     * @param inputMsg
     * @param accessToken
     * @throws Exception
     */
    private void memberCardEvent(InputMessage inputMsg,String accessToken)throws Exception {
        //需要的信息
        //性别
        String gender = "未知";
        //昵称

        String name = "";
        String mpbilePhone = "";
        String nickname = "";
        //查询激活信息
        String url = env.getProperty("weixinuri.getMemberCardUserInfoUrl").replace("ACCESS_TOKEN", accessToken);
        Map<String,Object> map = new HashMap<>(16);
        map.put("card_id",inputMsg.getCardId());
        map.put("code",inputMsg.getUserCardCode());
        // 构造出他想要的json字符串
        String openid4data = JsonUtil.toString(map);
        JSONObject json = WeixinHttpUtil.httpRequest(url, "POST", openid4data);
        String e = "0";
        //如果查询成功
        String errcode = "errcode";
        if (null != json && null != json.get(errcode)) {
            if (e.equals(json.get(errcode).toString())) {
                //性别
                String sex = "sex";
                if (null != json.get(sex)) {
                    gender = json.get(sex).toString();
                }
                //nickname 昵称
                nickname = "nickname";
                if (null != json.get(nickname)) {
                    nickname = json.get(nickname).toString();
                }
                String userI = "user_info";
                if (null != json.get(userI)) {
                    String userInfo = json.get(userI).toString();
                    if (!("").equals(userInfo)) {
                        //电话号码
                        String phoneType = "USER_FORM_INFO_FLAG_MOBILE";
                        //姓名
                        String nameType = "USER_FORM_INFO_FLAG_NAME";
                        String s = JSONObject.parseObject(userInfo).get("common_field_list").toString();
                        List<CommonFieldList> ts = JSONArray.parseArray(s, CommonFieldList.class);
                        for (int i = 0;i  < ts.size();i++) {
                            CommonFieldList common = ts.get(i);
                            if (phoneType.equals(common.getName())) {
                                mpbilePhone = common.getValue();
                            }
                            if (nameType.equals(common.getName())) {
                                name = common.getValue();
                            }
                        }
                    }
                }

            }
        }
        // 更新或新增数据
        insetOrUpdateData(gender,name,mpbilePhone,inputMsg,nickname);
    }

    /**
     * 数据处理（激活会员卡信息）
     * @param gender
     * @param name
     * @param mpbilePhone
     * @param inputMsg
     * @param nickName
     * @throws Exception
     */
    private void insetOrUpdateData(String gender,String name,String mpbilePhone,InputMessage inputMsg,String nickName) throws  Exception {
//        // 发送方帐号（open_id）
//        String fromUserName = inputMsg.getFromUserName();
//
//        //查询卡卷信息
//        Long id = null;
//        MemberCard memberCard = new MemberCard();
//        memberCard.setWeChatCardId(inputMsg.getCardId());
//        MemberCard byMemberCard = memberCardMapper.queryByMemberCard(memberCard);
//        Long createBy = byMemberCard.getCreatedBy();
//        Long corpId = byMemberCard.getCorpid();
//        if (null == corpId) {
//            corpId = 102L;
//        }
//        if (null == createBy) {
//            createBy = 0L;
//        }
//        Subscriber sub = new Subscriber();
//        sub.setOpenid(fromUserName);
//        sub.setPageFlag(false);
//        sub.setLoginCorpId(corpId);
//        List<Subscriber> subscriberList = wxSubscriberMapper.queryByExamplePage(sub);
//
//        Account account = new Account();
//        account.setPageFlag(false);
//        account.setWxOwnOpenId(fromUserName);
//        account.setLoginCorpId(corpId);
//        List<Account> accountList = accountService.queryByExamplePage(account);
//
//        String unionid = inputMsg.getUnionId();
//        String source = "OfficialAccounts";
//        updateSubscriber(subscriberList,source,nickName,id,corpId,createBy,unionid,inputMsg,sub);
//        updateAccount(accountList,account,mpbilePhone,name,createBy,corpId);
//
//        //创建/更新会员数据
//
//        MpMember mpMember = new MpMember();
//        mpMember.setPageFlag(false);
//        mpMember.setTelephone(mpbilePhone);
//        mpMember.setLoginCorpId(corpId);
//        List<MpMember> mpMemberList = mpMemberMapper.queryByExamplePage(mpMember);
//        if (mpMemberList.size() > 0) {
//            //更新
//            MpMember mpm = mpMemberList.get(0);
//            mpm.setWeChatUnionId(unionid);
//            mpm.setName(name);
//            mpm.setGender(gender);
//            //状态为Y
//            mpm.setStatus("Y");
//            mpm.interfaceCreateData(createBy,createBy,corpId);
//            mpMemberMapper.mpMemberUpdateByInterface(mpm);
//        } else {
//            //新增
//            Long receptionId = keyGenerateDao.keyGenerate();
//            mpMember.setId(receptionId);
//            mpMember.setName(name);
//            mpMember.setGender(gender);
//            mpMember.setWeChatUnionId(unionid);
//            //已领卡
//            mpMember.setStatus("Received");
//            mpMember.interfaceCreateData(createBy,createBy,corpId);
//            mpMemberMapper.mpMemberInsertByInterface(mpMember);
//        }
//
//        updateMemberAccount(inputMsg,byMemberCard,createBy,corpId,unionid);
//        updateMemberCard(byMemberCard);
        // TODO: 2019-11-01 会员卡迁移之后的待修改

    }

    private void updateMemberCard(MemberCard memberCard) throws Exception {
//        int num = memberCard.getReceivedNum();
//        memberCard.setReceivedNum(num + 1);
//        memberCardMapper.updReceivedNum(memberCard);
        // TODO: 2019-11-01 会员卡迁移之后的待修改
    }

    private void updateMemberAccount(InputMessage inputMsg, MemberCard byMemberCard, Long createBy, Long corpId,String unionid) throws Exception {
        //记录领卡记录
//        MemberAccount memberAccount = new MemberAccount();
//        memberAccount.setStatus("Received");
//        memberAccount.setMemCardId(Long.valueOf(inputMsg.getCardId()));
//        MpMember member = new MpMember();
//        member.setWeChatUnionId(unionid);
//        member.setPageFlag(false);
//        member.setLoginCorpId(corpId);
//        List<MpMember> memberList = mpMemberMapper.queryByExamplePage(member);
//        if (memberList.size() > 0) {
//            memberAccount.setMemberId(memberList.get(0).getId());
//        }
//        //查询有效期
//
//        if ( null != byMemberCard) {
//            memberAccount.setEffectEndDay(byMemberCard.getEffectEndTIme());
//            memberAccount.setEffectStartDay(byMemberCard.getEffectStartTime());
//        }
//        Long receptionId = keyGenerateDao.keyGenerate();
//        memberAccount.setId(receptionId);
//        memberAccount.interfaceCreateData(createBy,createBy,corpId);
//        memberAccountMapper.memberAccountInsertByInterface(memberAccount);
        // TODO: 2019-11-01 会员卡迁移之后的待修改
    }

    /**
     * 更新消费者信息
     * @param accountList
     * @param account
     * @param mpbilePhone
     * @param name
     * @param createBy
     * @param corpId
     * @throws Exception
     */
    private void updateAccount(List<Account> accountList, Account account, String mpbilePhone,
                               String name, Long createBy, Long corpId) throws Exception {
        //更新消费者（客户表）
        String accType = "WEIXIN";
        if (accountList.size() > 0) {
            //更新消费者信息
            Account act = accountList.get(0);
            act.setMobilePhone(mpbilePhone);
            act.setAcctName(name);
            act.setAcctType(accType);
            act.interfaceCreateData(createBy,createBy,corpId);
            accountMapper.accountUpdateByInterface(act);
        } else {
            //新增消费者数据
            Long receptionId = keyGenerateDao.keyGenerate();
            account.setId(receptionId);
            account.setMobilePhone(mpbilePhone);
            account.setAcctName(name);
            account.setAcctType(accType);
            account.interfaceCreateData(createBy,createBy,corpId);
            accountMapper.accountInsertByInterface(account);
        }
    }

    /**
     * 更新粉丝信息
     * @param subscriberList
     * @param source
     * @param nickName
     * @param id
     * @param corpId
     * @param createBy
     * @param unionid
     * @param inputMsg
     * @param sub
     */
    private void updateSubscriber(List<Subscriber> subscriberList, String source,
                                  String nickName, Long id, Long corpId, Long createBy,
                                  String unionid, InputMessage inputMsg, Subscriber sub) {
        if (subscriberList.size() > 0) {
            //更新粉丝信息
            Subscriber subr = subscriberList.get(0);
            unionid = subr.getUnionid();
            subr.setSource(source);
            subr.setNickname(nickName);
            if (null != id) {
                subr.setAccountId(id);
            }
            subr.interfaceCreateData(createBy,createBy,corpId);
            wxSubscriberMapper.subscriberUpdateByInterface(subr);

        } else {
            sub.setSource(source);
            sub.setNickname(nickName);
            if (null != id) {
                sub.setAccountId(id);
            }
            Long receptionId = keyGenerateDao.keyGenerate();
            sub.setId(receptionId);
            sub.setOpenid(inputMsg.getFromUserName());
            sub.setUnionid(unionid);
            sub.setOgId(inputMsg.getToUserName());
            sub.interfaceCreateData(createBy,createBy,corpId);
            wxSubscriberMapper.subscriberInsertByInterface(sub);
        }
    }

    /**
     * 处理用户删除会员卡或者重新领回会员卡事件
     *
     * @author KuangRuifeng
     * @date 2018年12月5日
     * @param inputMessage  推送通知信息
     * @param accessToken token
     * @param status 更新后的状态
     * @throws Exception 异常信息
     */
    private void updUserCard(InputMessage inputMessage, String accessToken, String status) throws Exception {
        String cardId = inputMessage.getCardId();
        String cardCode = inputMessage.getUserCardCode();
        // 先根据cardId查询卡券是否是会员卡
        String url = env.getProperty("weixinuri.cardDetailUrl").replace("ACCESS_TOKEN", accessToken);
        // 构造查询用的cardId信息
        Map<String, String> map = new HashMap<>(1);
        map.put("card_id", cardId);
        String cardIdStr = JsonUtil.toString(map);
        JSONObject resultJson = WeixinHttpUtil.httpRequest(url, "POST", cardIdStr);
        // 查询成功的信息
        String successmsg = "ok";
        String errmsg = "errmsg";
        if (!resultJson.get(errmsg).equals(successmsg)) {
            throw new ServiceException("WECHAT-008", resultJson.get("errmsg").toString());
        }
        JSONObject cardJson = JsonUtil.toJsonObject(JsonUtil.toString(resultJson.get("card")));
        // 卡券的类型
        String cardType = "card_type";
        // 会员卡类型的卡券
        String memberCardType = "MEMBER_CARD";
        // 目前只对会员卡类型的卡券进行更新
        if (cardJson.get(cardType).equals(memberCardType)) {
//            // 查询出此会员卡在内部系统的id
//            MemberCard memberCard = new MemberCard();
//            memberCard.setWeChatCardId(cardId);
//            memberCard = memberCardMapper.queryByMemberCard(memberCard);
//            MemberAccount memberAccount = new MemberAccount();
//            memberAccount.setMemCardCode(cardCode);
//            memberAccount.setMemCardId(memberCard.getId());
//            // 根据code和会员卡id查询出中间表关联关系
//            memberAccount = memberAccountMapper.queryByCode(memberAccount);
//            memberAccount.setStatus(status);
//            // 更新状态
//            memberAccountMapper.updateStatus(memberAccount);
            // TODO: 2019-11-01 会员卡迁移之后的待修改
        }
    }
}
